<?php

namespace App\Models;

use App\Enums\BucketType;
use App\Extends\Oss\OssConfig;
use App\Models\Traits\BelongsToApplication;
use Dcat\Admin\Admin;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ObjectStorageService extends Model
{
    use BelongsToApplication,
        SoftDeletes;

    protected $casts = [
        'type' => BucketType::class,
        'is_mine' => 'bool',
    ];

    protected static function boot(): void
    {
        parent::boot();

        self::creating(function (ObjectStorageService $service) {
            $service->is_mine = $service->application->admin->is(Admin::user());
        });
    }

    /**
     * Notes   : 所属阿里云账户
     *
     * @Date   : 2024/8/1 上午10:30
     * @Author : <Jason.C>
     * @return BelongsTo
     */
    public function aliyun(): BelongsTo
    {
        return $this->belongsTo(Aliyun::class);
    }

    /**
     * Notes   :
     *
     * @Date   : 2024/8/12 下午4:46
     * @Author : <Jason.C>
     * @param  string|null  $cdnHost
     * @param  bool  $useSsl
     * @return Filesystem
     */
    public function storage(?string $cdnHost = null, bool $useSsl = false): Filesystem
    {
        $config = new OssConfig(
            accessKey: $this->aliyun->app_id,
            secretKey: $this->aliyun->app_secret,
            endpoint: Str::after($this->bucket, '.'),
            cdnHost: $cdnHost,
            useSsl: $useSsl
        );

        return Storage::build([
            'bucket' => Str::before($this->bucket, '.'),
            'driver' => 'oss',
            'config' => $config,
        ]);
    }
}
